'use strict';

const { Controller } = require('egg');

class GoodUnitController extends Controller {
  async index() {
    const { ctx } = this;

    let dataList = {};
    let userId = ctx.session.userId;
    const d = await ctx.service.userInfo.find({id: userId})
    dataList.d = d;
    await this.ctx.render('masterData/goodUnit.njk', dataList);
  }

  async find() {
    const { ctx } = this;
    const goodsInfo = ctx.query;
    ctx.set('Content-Type', 'application/json');

    let opts = { orders: [ ['id', 'desc'] ] }
    opts.offset = goodsInfo.page ? (parseInt(goodsInfo.page) - 1) * (parseInt(goodsInfo.limit) || 10) : 0;
    opts.limit = goodsInfo.limit ? parseInt(goodsInfo.limit) : 10;
    delete goodsInfo.page;
    delete goodsInfo.limit;
    delete goodsInfo._csrf;

    for(let key in goodsInfo){
      if(goodsInfo[key] == '') delete goodsInfo[key]; //如果条件字段值为空，删除此字段。
    }
    opts.where = goodsInfo;
  
    const d = await ctx.service.masterData.goodUnit.find(opts)
    const maxCount = d.maxCount;
    delete d.maxCount;

    ctx.body = {
        code: 0,
        count: maxCount ? maxCount : (d.length || 1),
        data: d.length ? d : [d]
    };
  }

  async add() {
    const { ctx } = this;
    const goodsInfo = ctx.request.body;

    if( goodsInfo._csrf ) delete goodsInfo._csrf;
    goodsInfo.enable = goodsInfo.enable == 'on' ? 1 : 0;

    const result = await ctx.service.masterData.goodUnit.add(goodsInfo)
    
    let msg = '新增成功';
    if (result == -2){
      msg = '数据已存在!';
    }else if (result < 0) {
      msg = '参数不正确！';
    }

    ctx.body = {
      code: result < 0 ? 403 : 200,
      message: msg
    };
  }

  async update() {
    const { ctx } = this;

    const goodsInfo = ctx.request.body;
    if( goodsInfo._csrf ) delete goodsInfo._csrf;
    goodsInfo.enable = goodsInfo.enable == 'on' ? 1 : 0;
  
    const result = await ctx.service.masterData.goodUnit.update(goodsInfo)

    ctx.body = {
      code: result < 0 ? 403 : 200,
      message: result < 1 ? '请求参数不正确！' : '更新完成'
    };
  }

  async del() {
    const { ctx } = this;

    const id = ctx.params.id;
    if( !id ){
      ctx.body = {
        code: 403, message: '请求参数不正确！'
      }
    }else {
      const result = await ctx.service.masterData.goodUnit.del(id)

      ctx.body = {
        code: 200, message: result < 1 ? '删除不成功！' : '删除成功！'
      };
    }
  }

  async batchRemove() {
    const {ctx} = this;
    const ids = ctx.params.id;
  
    if( !ids ){
      ctx.body = {
        code: 403, message: '请求参数不正确！'
      }
    }else {
      const result = await ctx.service.masterData.goodUnit.batchRemove(ids)

      ctx.body = {
        code: 200, message: result < 1 ? '删除不成功！' : '删除成功！'
      };
    }
  }
}

module.exports = GoodUnitController;
